package com.hrbxlh.actionImpl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import jxl.Sheet;
import jxl.Workbook;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hrbxlh.dao.ChapterDao;
import com.hrbxlh.dao.ClassDao;
import com.hrbxlh.dao.CourseDao;
import com.hrbxlh.dao.HomeworkTestDao;
import com.hrbxlh.dao.MyCourseDao;
import com.hrbxlh.dao.ProfessionDao;
import com.hrbxlh.dao.QuestionDao;
import com.hrbxlh.dao.RelStuClassDao;
import com.hrbxlh.dao.RelationDao;
import com.hrbxlh.dao.SourceDao;
import com.hrbxlh.util.PubMethods;
import com.hrbxlh.util.pageUtil;

@Component("sourceActionImpl")
@Transactional
public class SourceActionImpl {
	
	@Resource(name="sourceDao")
	private SourceDao sourceDao;
	
	@Resource(name = "professionDao")
	private ProfessionDao professionDao;
	
	@Resource(name = "classDao")
	private ClassDao classDao;
	
	@Resource(name="courseDao")
	private CourseDao courseDao;
	
	@Resource(name = "relStuClassDao")
	private RelStuClassDao relStuClassDao;
	
	@Resource(name="homeworkTestDao")
	private HomeworkTestDao homeworkTestDao;
	
	@Resource(name="myCourseDao")
	private MyCourseDao myCourseDao;
	
	@Autowired
	@Qualifier("relationActionImpl")
	private RelationActionImpl relationActionImpl;
	
	@Resource(name="questionDao")
	private QuestionDao questionDao;

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  学生成绩列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getAllSourceList(Map<String, Object> paramMap,HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
			paramMap.put("stuorteaId", stuorteaId);
			//通过教师号获取此教师所属班级
			List<String> classList = relStuClassDao.getClassByStuorteaId(paramMap);
			if(classList!=null&&classList.size()!=0){
				paramMap.put("classList", classList);
				//通过教师号获取此教师所属课程
				List<Map<String,Object>> courseList = courseDao.getTeaTeachCourse(paramMap);
				if(courseList!=null&&courseList.size()!=0){
					paramMap.put("courseList", courseList);
					List<Map<String, Object>> memberList = sourceDao.getAllSourceList(paramMap);
					returnMap.put("memberList", memberList);
					returnMap.put("pageNow", pageNow);
					returnMap.put("classList", classList);
					//获取全部页数
					paramMap.put("pageNow", 0);
					List<Map<String, Object>> allMemberList = sourceDao.getAllSourceList(paramMap);
					int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
					returnMap.put("totalPage", totalPage);
					System.out.println("最后的map"+paramMap);
				}else{
					returnMap.put("memberList", null);
					returnMap.put("pageNow", 1);
					returnMap.put("totalPage", 0);
					returnMap.put("classList", null);
				}
				
			}else{
				returnMap.put("memberList", null);
				returnMap.put("pageNow", 1);
				returnMap.put("totalPage", 0);
				returnMap.put("classList", null);
			}
			//通过教师号获取此教师所属课程
			List<Map<String,Object>> courseList = courseDao.getTeaTeachCourse(paramMap);
			returnMap.put("courseList", courseList);
			
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
		 public boolean imStuSoruce(String file,HttpSession session) throws Exception{
			//得到表格中所有的数据
	       List<Map<String, Object>> listExcel= this.getAllByExcel(file);
	       boolean flag =false;
	       Map<String,Object> paramMap = new HashMap<String,Object>();
	       //获取当前登陆人的工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
			paramMap.put("stuorteaId", stuorteaId);
	       if(listExcel!=null){
	    	   System.out.println("imStuSoruce得到表格中所有的数据"+listExcel.size());
	    	   for (int i=0;i<listExcel.size();i++) {
	    		   //从成绩表中查询成绩权重
	    		   //查询每个班级分数最高人的分数
	    		   List<Map<String, Object>> memList = sourceDao.getMaxPreforSource(listExcel.get(i));
	    		   System.out.println("#########"+listExcel.get(i)+"查询每个班级分数最高人的分数"+memList);
	    	    	//查询课堂权重。
	    		   Map<String,Object> sorceMap = sourceDao.getProWedith(paramMap);
	    		   BigDecimal wedith = (BigDecimal) sorceMap.get("classPerformance");
	    		   System.out.println("权重是多少啊"+wedith);
	    		   BigDecimal finPromaceSource = new BigDecimal(0);
	    		   //分子固定、
	    		   BigDecimal explamSource = new BigDecimal(100);
	    		   //总权重
	    		   BigDecimal allWedith = new BigDecimal(1);
	    		   if(memList!=null&&memList.size()!=0){
	    			  String tempSource = String.valueOf(memList.get(0).get("maxpreforSource"));
	    			  System.out.println("tempSource"+tempSource);
	    			  if(tempSource!=null&&!(tempSource.equals("null"))){
	    				  //当前班级最高分
	    				  BigDecimal maxSource = new BigDecimal(tempSource);
	    				  //当前学生分数
	    				  String tempNowSource = String.valueOf(listExcel.get(i).get("preforSource"));
	    				  BigDecimal nowSource = new BigDecimal(tempNowSource);
	    				  //除
	    				  BigDecimal divSource = explamSource.divide(maxSource,2,BigDecimal.ROUND_HALF_EVEN);
	    				  //乘
	    				  BigDecimal mulSource = nowSource.multiply(divSource);
	    				  finPromaceSource = mulSource.multiply(wedith);
	    			  }
	    			
	    			  //学生的考试成绩
	    			  BigDecimal examSource = new BigDecimal(String.valueOf(listExcel.get(i).get("exam"))); 
	    			  //考试成绩的权重值(减) b1.subtract(b2)
	    			  BigDecimal examWedith = allWedith.subtract(wedith);
	    			  //学生考试成绩乘以权重
	    			  BigDecimal finalExamSource = examSource.multiply(examWedith);
	    			  //学生最后的成绩
	    			  BigDecimal finSumSource = finPromaceSource.add(finalExamSource);
	    			  listExcel.get(i).put("sumSource", finSumSource);
	    			  System.out.println("最后的成绩是多少"+listExcel.get(i).get("sumSource"));
	    			 
	    		   }else{
	    			   System.out.println("次班级学生没有成绩");
	    		   }
	    		   
	           }
	    	   
	    	   //查询成绩表是否有数据
	    	   List<Map<String, Object>> sourceList = sourceDao.getExam();
	    	 
	    	   if(sourceList!=null&&sourceList.size()!=0){
	    		   //通过学号删除学生原来的成绩信息，重新插入更新
	    	      flag = sourceDao.delSoruceBystuorteaId(listExcel);
	    	   }else{
	    		   flag = true;
	    	   }
	    	
	           System.out.println("最后添加的Map"+listExcel);
	           if(flag){
	        	   boolean flag1 = sourceDao.addSource(listExcel);
	        	   if(flag1){
	        		   System.out.println("导入成功");
	        	   }else{
	        		   System.out.println("导入失败");
	        	   }
	           }  
	       }else{
	    	   flag=false;
	       }
	       
	       return flag;
	   }
	 
	 /**
	    * 查询指定目录中电子表格中所有的数据
	    * @param file 文件完整路径
	    * @return
	    */
   public  List<Map<String, Object>> getAllByExcel(String file){
       List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
       try {
           Workbook rwb=Workbook.getWorkbook(new File(file));
           Sheet rs=rwb.getSheet(0);
           
           int clos=rs.getColumns();//得到所有的列
           int rows=rs.getRows();//得到所有的行
           
           System.out.println(clos+" rows:"+rows);
           int newRow = PubMethods.getSourceNewRows(rows, rs);
           ok:
           for (int i = 1; i < rows; i++) {
               for (int j = 0; j < clos; j++) {
            	   Map<String, Object> resultMap = new HashMap<String,Object>();
                   //第一个是列数，第二个是行数
            	   String stuorteaId=rs.getCell(j++, i).getContents().trim();
                   String userName=rs.getCell(j++, i).getContents().trim();//默认最左边编号也算一列 所以这里得j++
//                   String professionName=rs.getCell(j++, i).getContents().trim();
//                   System.out.println("professionName"+professionName);
                   //通过专业名查询专业id
//                   List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
                   Map<String, Object> paramMap = new HashMap<String,Object>();
//                   paramMap.put("professionName", professionName);
//                   returnList=professionDao.getProfessionList(paramMap);
//                   int professionId = Integer.parseInt(String.valueOf(returnList.get(0).get("professionId")));
                   //通过班级名查询班级id
                   String className=rs.getCell(j++, i).getContents().trim();
                   List<Map<String, Object>> classList = new ArrayList<Map<String, Object>>();
                   classList=classDao.getClassByClassName(className);
                   System.out.println("班级集合"+classList);
                   int classId=0;
                   if(classList!=null&&classList.size()!=0){
                	   classId = Integer.parseInt(String.valueOf(classList.get(0).get("classId")));
                   }
                   //通过课程名查询课程id
                   String courseName=rs.getCell(j++, i).getContents().trim();
                   System.out.println("courseName"+courseName);
                   paramMap.put("courseName", courseName);
                   Map<String, Object> courseMap = courseDao.getCourseDetailByName(paramMap);
                   System.out.println("怎么空指针了"+courseMap);
                   int courseId = 0;
                   if(courseMap!=null){
                	   courseId = Integer.valueOf(String.valueOf(courseMap.get("courseId")));
                   }
                   if(courseMap!=null&&classList!=null&&classList.size()!=0){
                	   //平时总分
                       String preformce=rs.getCell(j++, i).getContents().trim();
                       if(preformce.equals("")||preformce==null){
                    	   preformce="0";
                       }
                       BigDecimal preforSource = new BigDecimal(preformce);
                       //考试成绩
                       String exam=rs.getCell(j++, i).getContents().trim();
                       if(exam.equals("")||exam==null){
                    	   exam="0";
                       }
                       BigDecimal examSource = new BigDecimal(exam);
                       //总成绩
                       String sumSource=rs.getCell(j++, i).getContents().trim();
                       if(sumSource.equals("")||sumSource==null){
                    	   sumSource="0";
                       }
                       BigDecimal finsumSource = new BigDecimal(sumSource);
//                       System.out.println("userName"+userName+" stuorteaId:"+stuorteaId+" classId:"+classId+" professionId:"+professionId+"courseId"+courseId+"preforSource"+preforSource+"examSource"+examSource);
//                       resultMap.put("userName", userName);
                       resultMap.put("classId", classId);
                       resultMap.put("stuorteaId", stuorteaId);
//                       resultMap.put("professionId", professionId);
                       resultMap.put("courseId", courseId);
                       resultMap.put("preforSource", preforSource);
                       resultMap.put("exam", exam);
                       resultMap.put("sumSource", finsumSource);
                       list.add(resultMap);
                   }else{
                	   list = null;
                	   break ok;
                   }
                  
               }
           }
       } catch (Exception e) {
           
           e.printStackTrace();
       } 
       return list;
   }
   
   /**
	 * 查询成绩设置。
	 * @throws IOException
	 */
	public Map<String, Object> getProWedith(HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
			paramMap.put("stuorteaId", stuorteaId);
			Map<String, Object> sorceMap = sourceDao.getProWedith(paramMap);
			returnMap.put("sorceMap", sorceMap);
			
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 * 成绩设置。
	 * @throws IOException
	 */
	public Map<String,Object> addSorceSet(Map<String,Object> paramMap,HttpSession session) throws Exception {
		
		boolean flag = false;
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			
			//获取当前登陆人的工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
			paramMap.put("stuorteaId", stuorteaId);
			
			//查询该教师下的学生是否已经有成绩
			List<Map<String, Object>> sourceList = sourceDao.getExamByteaId(paramMap);
			if(sourceList==null||sourceList.size()==0){
				//查询成绩设置是否已经有数据，如果有数据则做更新操作
				Map<String,Object> resultMap = sourceDao.getProWedith(paramMap);
				if(resultMap!=null){
					flag = sourceDao.updateSorceSet(paramMap);
					map.put("flag", flag);
					map.put("errMsg", "成功");
				}else{
					flag = sourceDao.addSorceSet(paramMap);
					map.put("flag", flag);
					map.put("errMsg", "成功");
				}
			}else{
				map.put("flag", flag);
				map.put("errMsg", "已有成绩不可更改权重");
			}
			
		} catch (Exception e) {
			throw e;
		}
		return map;
	}
	
	/**
	 * @param 学生成绩详情
	 * @throws IOException
	 */
	public Map<String, Object> getStuSourceDetail(Map<String, Object> paramMap,HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			
//			//查询当前要评价学生所在班级所属课程(参数是学号、课程号)
//			Map<String,Object> stuClaCouMap = relStuClassDao.getStuClaAndCou(paramMap);//这个结果里有班号
//			//查询当前班级当前课程相关学生的平时成绩(参数是班号、课程号)
//			List<Map<String,Object>> stuList = sourceDao.getStuSourceList(paramMap);
//			//将和此评价学生所在同一所班级的学生总成绩重新计算后更改数据库(参数是班号、课程号)
//			sourceDao.updateSorceBySId(paramMap);
			
			//通过学号和课程号获取此学生成绩
			Map<String, Object> detailMap = sourceDao.getExamBySidAndCourseId(paramMap);
			//平时成绩换算值(参数是班号、课程号、学生平时分)
			BigDecimal finPromaceSource = this.proSource(paramMap, detailMap,session);
			//考试成绩换算值（参数考试成绩）
			BigDecimal examSource = this.examSource(paramMap, detailMap,session);
			detailMap.put("finPromaceSource", finPromaceSource);
			detailMap.put("finExamSource", examSource);
			//学生最后的成绩
		   BigDecimal finSumSource = finPromaceSource.add(examSource);
		   paramMap.put("sumSource", finSumSource);
		   paramMap.put("examSource", examSource);
		   System.out.println("编辑成绩表，将学生总成绩插入数据库"+paramMap+"平时成绩"+finPromaceSource+"考试成绩"+examSource+"考试总成绩"+finSumSource);
			//将前台传过来的学号取出来在重新存进参数Map中获取当前学生的章节细节（因为在上步求平时成绩和考试成绩换算值时stuorteaId已经变成教师id了所以在这要重新把前台传的学号弄回来）
			String id = (String) paramMap.get("parameStuorteaId");
			paramMap.put("stuorteaId", id);
			System.out.println("最后的map"+paramMap);
			//编辑成绩表，将学生总成绩插入数据库。
			  paramMap.put("type", 1);
			  questionDao.saveQuestionByStuId(paramMap);
			  detailMap.put("sumSource", finSumSource);
			  System.out.println("zui="+detailMap.get("source"));
			  returnMap.put("detailMap", detailMap);
			//通过学号和课程号获取此学生课程中每章节的分数
			List<Map<String,Object>> courseList = homeworkTestDao.getEverySourceByCourseAndSid(paramMap);
			returnMap.put("courseList", courseList);
			
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  学生成绩列表页面(学生)。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getStuAllSourceList(Map<String, Object> paramMap,HttpSession session) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			String stuorteaId = (String) session.getAttribute("stuorteaId");
			paramMap.put("stuorteaId", stuorteaId);
			System.out.println("最后的map"+paramMap);
			//通过学生获取此学生所属课程
			List<Map<String,Object>> courseList = myCourseDao.getStuCourse(paramMap);
			returnMap.put("courseList", courseList);
			List<Map<String, Object>> memberList = sourceDao.getStuAllSourceList(paramMap);
			returnMap.put("memberList", memberList);
			returnMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allMemberList = sourceDao.getStuAllSourceList(paramMap);
			int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
			returnMap.put("totalPage", totalPage);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	
	//平时成绩转换值
		public BigDecimal proSource(Map<String,Object> paramMap,Map<String,Object> detailMap,HttpSession session ) throws Exception{
			System.out.println("查询班级最高分的参数是啥"+paramMap);
			//查询每个班级分数最高人的分数
			   List<Map<String, Object>> memList = sourceDao.getMaxPreforSource(paramMap);
			   System.out.println("查询每个班级分数最高人的分数"+memList);
			   String stuorteaId = this.getId(session,paramMap);
			   String parameStuorteaId = (String) paramMap.get("stuorteaId");
			   paramMap.put("parameStuorteaId", parameStuorteaId);
			   paramMap.put("stuorteaId", stuorteaId);
				System.out.println("参数是啥啊"+paramMap);
			   //查询课堂权重。
			   Map<String,Object> sorceMap = sourceDao.getProWedith(paramMap);
			   System.out.println("是空呗"+sorceMap);
			   BigDecimal wedith = (BigDecimal) sorceMap.get("classPerformance");
			   System.out.println("权重是多少啊"+wedith+"参数是啥啊"+paramMap+"detailMap"+detailMap);
			   BigDecimal finPromaceSource = new BigDecimal(0);
			   //分子固定、
			   BigDecimal explamSource = new BigDecimal(100);
			   //总权重
			   BigDecimal allWedith = new BigDecimal(1);
			   if(memList!=null&&memList.size()!=0){
				  String tempSource = String.valueOf(memList.get(0).get("maxpreforSource"));
				  System.out.println("tempSource"+tempSource);
				  if(tempSource!=null&&!(tempSource.equals("null"))&&!(tempSource.equals("0"))&&!(tempSource.equals("0.00"))){
					  //当前班级最高分
					  BigDecimal maxSource = new BigDecimal(tempSource);
					  //当前学生分数
					  String tempNowSource = String.valueOf(detailMap.get("preforSource"));
					  BigDecimal nowSource = new BigDecimal(tempNowSource);
					  System.out.println("maxSource"+maxSource+"explamSource"+explamSource);
					  //除
					  BigDecimal divSource = explamSource.divide(maxSource,2,BigDecimal.ROUND_HALF_EVEN);
					  //乘
					  BigDecimal mulSource = nowSource.multiply(divSource);
					  finPromaceSource = mulSource.multiply(wedith).setScale(2,BigDecimal.ROUND_HALF_UP);
				  }
		   }
	   return finPromaceSource;
	  }
	
	//考试成绩转换值
		public BigDecimal examSource(Map<String,Object> paramMap,Map<String,Object> detailMap,HttpSession session ) throws Exception{
			 BigDecimal finExamSource = new BigDecimal(0);
			 	//获取当前登陆人的工号
				String stuorteaId = this.getId(session,paramMap);
				paramMap.put("stuorteaId", stuorteaId);
			   //查询课堂权重。
			   Map<String,Object> sorceMap = sourceDao.getProWedith(paramMap);
			   BigDecimal wedith = (BigDecimal) sorceMap.get("classPerformance");
			   System.out.println("权重是多少啊"+wedith);
			   //总权重
			   BigDecimal allWedith = new BigDecimal(1);
			   //考试成绩的权重值(减) b1.subtract(b2)
 			  BigDecimal examWedith = allWedith.subtract(wedith);
			  //当前学生考试分数
			  String tempExamSource = String.valueOf(detailMap.get("examSource"));
			  BigDecimal nowSource = new BigDecimal(tempExamSource);
			  //乘
			  BigDecimal mulSource = nowSource.multiply(examWedith).setScale(2,BigDecimal.ROUND_HALF_UP);
			  finExamSource = mulSource;
	   return finExamSource;
	  }
		//判断当前登陆人是老师还是学生返回相应的学号或工号
		public String getId(HttpSession session,Map<String,Object> map) throws Exception{
			String stuorteaId = "";
			Map<String,Object> paramMap = new HashMap<String,Object>();
			//获取当前登录人选择的角色
			int roleId = (Integer) session.getAttribute("roleId");
			//获取当前登陆人的id
			String nowId = (String) session.getAttribute("stuorteaId");
			paramMap.put("stuorteaId", nowId);
			if(roleId==1){
				System.out.println("说明当前登陆人是学生，则要获取此学生所属教师工号"+roleId+"   $$$$"+nowId+"paramMap"+paramMap);
				paramMap.put("roleId", 1);
				paramMap.put("courseId", map.get("courseId"));
				//说明当前登陆人是学生，则要获取此学生所属教师工号
				Map<String,Object> relMap = relationActionImpl.getMyTeacherByCourseId(paramMap);
				stuorteaId = (String) relMap.get("stuorteaId");
			}if(roleId==2){
				System.out.println("说明当前登陆人是教师，则直接从session获取当前登陆人的id"+roleId+"  %%%%"+nowId);
				//说明当前登陆人是教师，则直接从session获取当前登陆人的id
				stuorteaId = (String) session.getAttribute("stuorteaId");
			}
			System.out.println("最后的id是"+stuorteaId);
			return stuorteaId;
		}
}
